<template>
  <div>
    <!-- 搜索 -->
    <el-form ref="searchForm" :inline="true" :model="searchMap" style="margin-top:20px">
      <!-- 对于需要重置的字段需要加上prop=XX属性 -->
      <el-form-item prop="carNum">
        <el-input v-model="searchMap.carNum" placeholder="会员卡号"></el-input>
      </el-form-item>
        <el-form-item prop="name">
        <el-input v-model="searchMap.name" placeholder="会员名字"></el-input>
      </el-form-item>
      <el-form-item prop="payType">
        <el-select v-model="searchMap.payType" placeholder="支付方式">
          <el-option v-for="payType in payTypeOptions" :key="payType.type"  :label="payType.name" :value="payType.type"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="birthday">
              <el-date-picker value-format="yyyy-MM-dd" v-model="searchMap.birthday" type="date" placeholder="选择日期">
    </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  @click="fetchMember">查询</el-button>
        <el-button type="primary"  @click="toAdd">新增</el-button>
        <el-button   @click="resetForm('searchForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table border height="400" :data="list" style="width: 100%">
      <el-table-column type="index" label="序号"> </el-table-column>
      <el-table-column prop="carNum" label="卡号"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="90px"> </el-table-column>
      <el-table-column prop="birthday" label="生日"> </el-table-column>
      <el-table-column prop="phone" label="电话"> </el-table-column>
      <el-table-column prop="integeral" label="积分"> </el-table-column>
      <el-table-column prop="money" label="余额"> </el-table-column>
      <el-table-column prop="payType" label="支付方式">
        <template slot-scope="scope">
          <span>{{ scope.row.payType | payTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>
      <el-table-column label="操作" width="150px">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="rows"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 新增用户的弹窗 -->
    <el-dialog title="新增会员" :visible.sync="dialogFormVisible" width="500px">
  <el-form :rules="rule" ref="memberForm" label-width="100px" label-position="right" :model="member" style="width:400px">
    <el-form-item label="会员卡号" prop="cardNum" >
      <el-input v-model="member.cardNum" autocomplete="off"></el-input>
    </el-form-item>
        <el-form-item label="会员姓名" prop="name" >
      <el-input v-model="member.name" autocomplete="off"></el-input>
    </el-form-item>
        <el-form-item label="会员生日" prop="birthday" >
          <el-date-picker value-format="yyyy-MM-dd" v-model="member.birthday" type="date" placeholder="选择日期">
    </el-date-picker>
    </el-form-item >
        <el-form-item label="手机号码" prop="phone" >
      <el-input v-model="member.phone" autocomplete="off"></el-input>
    </el-form-item>
        <el-form-item label="可用积分" prop="integeral"  >
      <el-input v-model="member.integeral" autocomplete="off"></el-input>
    </el-form-item>
        <el-form-item label="开卡金额" prop="money"  >
      <el-input v-model="member.money" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="支付类型" prop="payType">
        <el-select v-model="member.payType" placeholder="支付方式">
          <el-option v-for="payType in payTypeOptions" :key="payType.type"  :label="payType.name" :value="payType.type"></el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="会员地址" prop="address"  >
      <el-input type="textarea" v-model="member.address" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="member.id === null ? addMember('memberForm') : updateOne('memberForm')">确 定</el-button>
  </div>
</el-dialog>
  </div>
</template>


<script>
import Member from "@/api/member";
//不能定义在vue实例里面，因为filter无法获取当前组件实例
const payTypeOptions = [
  { type: "1", name: "支付宝" },
  { type: "2", name: "微信" },
  { type: "3", name: "银行卡" },
  { type: "4", name: "现金" },
];
export default {
  data() {
    return {
      list: [],
      currentPage: 1, //当前页码
      rows: 10, //每页显示10条数据
      total: 0, //总记录数
      dialogFormVisible: false,
      member:{
        id:null,
        cardNum:"",
        name:"",
        birthday:"",
        phone:"",
        integeral:0,
        money:0,
        payType:"",
        address:"",
      },
      searchMap: { //查询条件对象
        carNum:"",
        name:"",
        payType:"",
        birthday:"",
      }, 
      payTypeOptions,
      rule:{
        cardNum:[
          { required: true, message: '请输入卡号', trigger: 'blur' },
        ],
        name:[
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        phone:[
          { required: true, message: '请输入电话号码', trigger: 'blur' },
        ],
        payType:[
          { required: true, message: '请输入支付方式', trigger: 'change' },
        ]
      }
    };
  },
  created() {
    this.fetchMember();
  },
  methods: {
    //添加会员
    addMember(memberForm){
      //校验提交的数据
        this.$refs[memberForm].validate(valid=>{
          if(valid){
            console.log("addMember");
            Member.addMember(this.member).then(res=>{
              const result = res.data;
              if(result.flag){
                //添加成功以后重新加载数据
                this.fetchMember();
                this.dialogFormVisible = false;
                this.$message({
                  message:result.msg,
                  type:"success",
                })
              }else{
                  this.$message({
                  message:result.msg,
                  type:"error",
                })
              }
            })
          }else{
            return false;
          }
        })
    },
    //重置新增会员表单的内容
    toAdd(){
      this.dialogFormVisible = true;
      //this.$nextTick 是一个异步事件，当渲染结束以后，它的回调函数才会被执行
      // 弹出窗口打开之后，就需要加载dom，就需要花费一点时间，我们就应该等待它加载完毕dom之后，再进行resetFields方法，重置表单和清除样式
      this.$nextTick(()=>{  
        this.$refs['memberForm'].resetFields();
      })
    },
    //重置表单
    resetForm(formName){
      this.$refs[formName].resetFields();
    },
    //每页显示更改以后触发的函数
    handleSizeChange(val){
      this.rows = val;
      this.fetchMember();
    },
    //当前页码更改以后触发的函数
    handleCurrentChange(val){
      this.currentPage = val;
      this.fetchMember();
    },
    //查找所有会员的函数
    fetchMember() {
      //   Member.getList().then((res) => {
      //进行分页查询
      Member.getListPage(this.currentPage, this.rows, this.searchMap).then(
        (res) => {
          const result = res.data;
          this.list = result.data.rows;
          this.total = result.data.total;
          console.log(result.data.rows);
        }
      );
    },
    //编辑和删除的函数
    handleEdit(id) {
      console.log(id);
      Member.getOne(id).then(res=>{
        const result = res.data;
        if(result.flag){
          this.member = result.data;
          this.toAdd();
        }else{
          this.$message({
            message:result.msg,
            type:"error",
          })
        }
      })
    },
    //更新会员信息
    updateOne(formName){
      //更新之前也需要对数据进行校验
      this.$refs[formName].validate(valid=>{
        if(valid){
          Member.EditOne(this.member).then(res=>{
            const result = res.data;
            if(result.flag){
              this.dialogFormVisible = false;
              this.$message({
                message:result.msg,
                type:"success",
              })
            }else{
              this.$message({
                message:result.msg,
                type:"error",
              })
            }
          })
        }
      })
    },
    //删除会员的函数
    handleDelete(id) {
      console.log(id);
          this.$confirm('此操作将删除会员信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //确定删除
          Member.deleteOne(id).then(res=>{
            const result = res.data;
            if(result.flag){
              //删除以后重新加载数据
              this.fetchMember();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }else{
              this.$message({
                type: 'error',
                message: '删除失败!'
          });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          });          
        });
    },
  },
  //针对支付方式数组过滤转换
  filters: {
    payTypeFilter(payType) {
      const payObj = payTypeOptions.find((obj) => {
        return obj.type === payType;
      });
      //防止脏数据
      return payObj ? payObj.name : null;
    },
  },
};
</script>